package com.mlethe.android.demo.seattable.base;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public abstract class BaseFragment<P extends BasePresenter, V extends IView> extends Fragment {

    protected View rootView;

    protected P iPresenter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        iPresenter = createPresenter();
        if (iPresenter != null) {
            iPresenter.attachView((V)this);
            iPresenter.onCreate();
        }
        rootView = View.inflate(getActivity(), getLayoutId(), null);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    protected abstract P createPresenter();

    protected abstract void initData();

    protected abstract void initView();

    protected abstract int getLayoutId();

    @Override
    public void onStart() {
        super.onStart();
        if (iPresenter != null) {
            iPresenter.onStart();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (iPresenter != null) {
            iPresenter.onResume();
        }
    }

    @Override
    public void onPause() {
        if (iPresenter != null) {
            iPresenter.onPause();
        }
        super.onPause();
    }

    @Override
    public void onStop() {
        if (iPresenter != null) {
            iPresenter.onStop();
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        if (iPresenter != null) {
            iPresenter.detachView();
            iPresenter.onDestroy();
        }
        super.onDestroy();
    }
}
